package com.jzo2o.foundations.xxjob;

import cn.hutool.json.JSONUtil;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeSearch;
import com.jzo2o.foundations.service.IRegionServeService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * \* User: chy
 * \* Date: 2025/9/29  14:32
 * \* Description:
 * \
 */
@Component
@Slf4j
public class InitCopyServeToEsJob {

    @Resource
    private ServeMapper serveMapper;
    @Resource
    private RestHighLevelClient esClient;
    @XxlJob("initCopyServeToEsJob")
    //todo:批量从数据库中查询所有在售的服务列表到es中  需要用到RestHighLevelClient 进行实例化bean在config配置文件中
    public void initCopyServeToEsJob(){
        log.info("初始化服务数据到es任务开始执行");
        // 1.查询所有在售的服务列表
        List<ServeSearch> serveList = serveMapper.queryAllSaleServeList();
        if(CollectionUtils.isEmpty(serveList)){
            log.info("没有在售的服务列表");
            return;
        }
        // 2.创建批量请求
        BulkRequest bulkRequest = new BulkRequest("serve");
        for (ServeSearch serve : serveList) {
            // 创建索引请求
            IndexRequest indexRequest = new IndexRequest();
            // 设置索引id
            indexRequest.id(serve.getId()+"");
            // 设置数据
            indexRequest.source(JSONUtil.toJsonStr( serve), XContentType.JSON);
            // 添加到批量请求
            bulkRequest.add(indexRequest);
        }
        try {
            // 3.执行批量请求
            esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("初始化服务数据到es任务执行异常",e);
        }
        log.info("初始化服务数据到es任务执行完毕");
    }
}
